<?php

namespace App\Services\TransferGoldCoin;

use App\Models\User;
use Illuminate\Support\Facades\DB;

class TransferGoldCoin
{
	/**
	 * @var User
	 */
	protected $self;

	/**
	 * @var User
	 */
	protected $target;

	protected $coins = 0;

	protected $payCode = null;

	public function __construct(User $self, User $target, $coins, $payCode = null)
	{
		$this->self = $self;
		$this->target = $target;
		$this->coins = $coins;
		$this->payCode = $payCode;
	}

	protected function transfer()
	{
		DB::transaction(function () {
			$data = ['target_user_id' => $this->target->id];
			account_coins($this->self)->minusTransferedCoins($this->coins, $data);

			$data = ['self_user_id' => $this->self->id];
			account_coins($this->target)->plusTransferedCoins($this->coins, $data);
		});
	}

	public function apply()
	{
		if (empty($this->payCode)) {
			return;
		}

		$this->transfer();
	}
}
